/**   
* @Description: 参数校验处理器入口 
*/ 
package org.kskj.ipw.validator;

import java.lang.annotation.Annotation;
import java.lang.reflect.Method;
import java.lang.reflect.Parameter;
import java.util.HashMap;
import java.util.Map;

import org.aspectj.lang.JoinPoint;
import org.kskj.ipw.exception.ValidateException;
import org.kskj.ipw.validator.handle.IsDigitValidatorHandle;
import org.kskj.ipw.validator.handle.ValidatorHandle;

/** 
* @author sztan 
* @date 2016年8月5日 下午4:49:45 
* @version 1.0 
*/
public class ParamValidatorProcess {
	private static Map<String, Object> validatorHandleMap = new HashMap<String, Object>();
	
	static {
		// 初始化默认处理类
		validatorHandleMap.put("IsDigit", new IsDigitValidatorHandle());
	}
	
	private ParamValidatorProcess() {
		// 不提供创建实例
	}
	
	public static void paramValidator(JoinPoint joinPoint) throws ValidateException{
		Object[] args = joinPoint.getArgs();
		Method[] methods = joinPoint.getTarget().getClass().getMethods();
		Method checkMethod = null;
		for (Method method : methods) {
			if (joinPoint.getSignature().getName().equals(method.getName())) {
				checkMethod = method;
				break;
			}
		}
		
		if (null != checkMethod) {
			// 获取参数
			Parameter[] parameters = checkMethod.getParameters();
			for (int i = 0; i <  parameters.length; i++) {
				checkParam(parameters[i], args[i]);
			}
		}
	}
	
	private static void checkParam(Parameter parameter, Object parameterValue) throws ValidateException{
		Annotation[] annotations = parameter.getAnnotations();
		ValidatorHandle handle = null;
		for (Annotation annotation : annotations) {
			handle = getValidatorHandle(annotation);
			if (null != handle) {
				handle.validate(annotation, parameterValue);
			}
		}
	}
	
	private static ValidatorHandle getValidatorHandle(Annotation annotation) {
		String annoName = annotation.annotationType().getCanonicalName();
		return (ValidatorHandle) validatorHandleMap.get(annoName.substring(annoName.lastIndexOf(".")+1));
	}
}
